﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class LocationListControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                RSUserIdentity userIdentity = GetRSUserIdentity();
                LoadCityDropdownList(userIdentity.RSCompanyId);
                LoadStateDropdownList(userIdentity.RSCompanyId);
                LoadCountyDropdownList(userIdentity.RSCompanyId);

                //int CompanyId = userIdentity.RSCompanyId;
                //
                //cf.ApplyGridViewColumnRule(this, CompanyId, "LocationListControl.ascx");
            }
        }
        public void LoadLocationListData(int companyid)
        {
            SqlCommand myCommand;
            String sqlSELECT = "select LocationId,LocationName,street,City,County,State,Country,Zip,Active,Note,CompanyId from rs_tblLocation ";
            String sqlWHERE = " where companyid=@companyid";

            List<string> paramlist = new List<string>();
            paramlist.Add("@companyid");

            if (txtLocationID.Text != "")
            {
                sqlWHERE = sqlWHERE + " and locationid=@locationid";
                paramlist.Add("@locationid");
            }
            else
            {
                if (txtStreet.Text != "")
                {
                    sqlWHERE = sqlWHERE + " and (CHARINDEX(@street, street) > 0)";
                    paramlist.Add("@street");
                }
                //if (txtFirstName.Text != "")
                //{
                //    sqlWHERE = sqlWHERE + " and firstname=@firstname";
                //    paramlist.Add("@firstname");
                //}
                //if (txtLastName.Text != "")
                //{
                //    sqlWHERE = sqlWHERE + " and lastname=@lastname";
                //    paramlist.Add("@lastname");
                //}
                if (ddlCity.SelectedValue != "")
                {
                    sqlWHERE = sqlWHERE + " and city=@city";
                    paramlist.Add("@city");
                }
                if (ddlState.SelectedValue != "")
                {
                    sqlWHERE = sqlWHERE + " and state=@state";
                    paramlist.Add("@state");
                }
                if (ddlCounty.SelectedValue != "")
                {
                    sqlWHERE = sqlWHERE + " and county=@county";
                    paramlist.Add("@county");
                }
            }

            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT + " " + sqlWHERE + " order by city, state, county", myConnection);

            for (int i = 0; i < paramlist.Count(); i++)
            {
                if (paramlist[i] == "@companyid")
                {
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@companyid";
                    param.Value = companyid;
                    myCommand.Parameters.Add(param);
                }
                if (paramlist[i] == "@locationid")
                {
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@locationid";
                    param.Value = int.Parse(txtLocationID.Text);
                    myCommand.Parameters.Add(param);
                }
                if (paramlist[i] == "@street")
                {
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.NVarChar;
                    param.ParameterName = "@street";
                    param.Value = txtStreet.Text.Trim();
                    myCommand.Parameters.Add(param);
                }
                //if (paramlist[i] == "@firstname")
                //{
                //    param = new SqlParameter();
                //    param.SqlDbType = SqlDbType.NVarChar;
                //    param.ParameterName = "@firstname";
                //    param.Value = txtFirstName.Text.Trim();
                //    myCommand.Parameters.Add(param);
                //}
                //if (paramlist[i] == "@lastname")
                //{
                //    param = new SqlParameter();
                //    param.SqlDbType = SqlDbType.NVarChar;
                //    param.ParameterName = "@lastname";
                //    param.Value = txtLastName.Text.Trim();
                //    myCommand.Parameters.Add(param);
                //}
                if (paramlist[i] == "@city")
                {
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.NVarChar;
                    param.ParameterName = "@city";
                    param.Value = ddlCity.SelectedValue;
                    myCommand.Parameters.Add(param);
                }
                if (paramlist[i] == "@state")
                {
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.NVarChar;
                    param.ParameterName = "@state";
                    param.Value = ddlState.SelectedValue;
                    myCommand.Parameters.Add(param);
                }
                if (paramlist[i] == "@county")
                {
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.NVarChar;
                    param.ParameterName = "@county";
                    param.Value = ddlCounty.SelectedValue;
                    myCommand.Parameters.Add(param);
                }
            }


            SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
            myConnection.Open();
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            Session["DATATABLE"] = ds.Tables[0];
            gvLocationList.DataSource = ds;
            gvLocationList.DataBind();
            lblLocationCount.Text = ds.Tables[0].Rows.Count.ToString();
            myConnection.Close();
        }

        protected void btnResetSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.RawUrl);
        }
        private void LoadCityDropdownList(int companyid)
        {
            SqlParameter param = new SqlParameter();
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "select distinct city from rs_tbllocation where companyid=@companyid order by city";
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);
            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlCity.Items.Clear();
            ddlCity.DataSource = myDataReader;
            ddlCity.DataTextField = "city";
            ddlCity.DataValueField = "city";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, new ListItem("", ""));
            myConnection.Close();
        }
        private void LoadStateDropdownList(int companyid)
        {
            SqlParameter param = new SqlParameter();
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "select distinct state from rs_tbllocation where companyid=@companyid order by state";
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);
            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlState.Items.Clear();
            ddlState.DataSource = myDataReader;
            ddlState.DataTextField = "state";
            ddlState.DataValueField = "state";
            ddlState.DataBind();
            ddlState.Items.Insert(0, new ListItem("", ""));
            myConnection.Close();
        }
        private void LoadCountyDropdownList(int companyid)
        {
            SqlParameter param = new SqlParameter();
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "select distinct county from rs_tbllocation where companyid=@companyid order by county";
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);
            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlCounty.Items.Clear();
            ddlCounty.DataSource = myDataReader;
            ddlCounty.DataTextField = "county";
            ddlCounty.DataValueField = "county";
            ddlCounty.DataBind();
            ddlCounty.Items.Insert(0, new ListItem("", ""));
            myConnection.Close();
        }
        protected void gvLocationList_DataBinding(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;
            
            RSSBMCommonFunctions.ApplyGridViewColumnRule(this, CompanyId, "LocationListControl.ascx");
        }
        protected void btnAddLocation_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                //Response.Redirect("~/RS/SBM/RSLocationDetail.aspx?action=add");
                ucModalManageLocationControl.ShowModal(userIdentity.RSCompanyId, 0);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
            
        }
        protected void gvLocation_Edit(object sender, CommandEventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int companyid = userIdentity.RSCompanyId;
            int locationid = Convert.ToInt32(e.CommandArgument.ToString());
            if (companyid > 0 && locationid > 0)
                ucModalManageLocationControl.ShowModal(companyid, locationid);
        }
        protected void lnkViewMap_Click(object sender, CommandEventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int companyid = userIdentity.RSCompanyId;
            int locationid = Convert.ToInt32(e.CommandArgument.ToString());
            
            if (companyid > 0 && locationid > 0)
                ucModalViewMapControl.ShowMapDataByLocationID(companyid, locationid);
        }
        protected void lnkViewAllOnMap_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int companyid = userIdentity.RSCompanyId;
            if (companyid > 0)
                ucModalViewMapControl.ShowMapAllLocations(companyid);
        }
        protected void gvLocationList_RowDeleting(Object sender, GridViewDeleteEventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int companyid = userIdentity.RSCompanyId;
                int locationid = Convert.ToInt32(gvLocationList.DataKeys[e.RowIndex].Value);
                DeleteLocation(companyid, locationid);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);

        }


        private void DeleteLocation(int companyid, int locationid)
        {
            if (companyid > 0 && locationid > 0)
            {
                SqlCommand sqlCmd = new SqlCommand();
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@locationid", SqlDbType.Int, 0, ParameterDirection.Input, locationid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
                SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblCallLocation WHERE LocationId=@locationid AND CompanyId=@companyid; DELETE FROM rs_tblContactLocation WHERE LocationId=@locationid AND CompanyId=@companyid; DELETE FROM rs_tblLocation WHERE LocationId=@locationid AND CompanyId=@companyid;");
                SQLHelper.ExecuteScalarCmd(sqlCmd);
                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                Response.Redirect(Request.RawUrl);
            }
        }


        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;

            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    newSortDirection = "ASC";
                    break;

                case SortDirection.Descending:
                    newSortDirection = "DESC";
                    break;
            }
            return newSortDirection;
        }

        protected void gvWorkOrderTasks_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvLocationList.PageIndex = e.NewPageIndex;
            gvLocationList.DataBind();
        }

        protected void gvWorkOrderTasks_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dataTable = Session["DATATABLE"] as DataTable;
            if (dataTable != null)
            {
                DataView dataView = new DataView(dataTable);
                dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

                gvLocationList.DataSource = dataView;
                gvLocationList.DataBind();
            }
        }

    }
}